<style>
.form-item{
 margin-top: 7%;
}
.video{
  width: 100px;
  margin-left: 20%;
}
</style>

<template>
  <div class="app-container">
<!--    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">-->
<!--      <el-form-item label="视频名称" prop="name">-->
<!--        <el-input-->
<!--          v-model="queryParams.name"-->
<!--          placeholder="请输入"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="" prop="fileUrl">-->
<!--        <el-input-->
<!--          v-model="queryParams.fileUrl"-->
<!--          placeholder="请输入"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="" prop="disasterId">-->
<!--        <el-input-->
<!--          v-model="queryParams.disasterId"-->
<!--          placeholder="请输入"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="" prop="picture">-->
<!--        <el-input-->
<!--          v-model="queryParams.picture"-->
<!--          placeholder="请输入"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
<!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:video:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:video:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:video:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="视频名称" align="center" prop="name" />
<!--      <el-table-column label="病情id" align="center" prop="disasterId" />-->
      <el-table-column label="视频封面" align="center" prop="picture">
        <template slot-scope="scope">
          <img :src="scope.row.picture" style="width: 100px; height: 100px;">
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:video:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:video:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <pagination-->
<!--      v-show="total>0"-->
<!--      :total="total"-->
<!--      :page.sync="queryParams.pageNum"-->
<!--      :limit.sync="queryParams.pageSize"-->
<!--      @pagination="getList"-->
<!--    />-->

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small" style="height: 400px; overflow-y: auto;">
        <el-form-item label="视频名称" prop="name" class="form-item">
          <el-input v-model="videoName" placeholder="请输入" />
        </el-form-item>
<!--        <el-form-item label="对应灾情" prop="fileUrl" class="form-item">-->
<!--          <el-select v-model="form.disasterId" placeholder="请选择">-->
<!--            &lt;!&ndash; <el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value"></el-option> &ndash;&gt;-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="封面上传" prop="picture" class="form-item">
          <el-upload
            :show-file-list="false"
            :action="uploadUrl"
            :headers="headers"
            :on-success="handleCoverSuccess"
            :before-upload="beforeUpload"
          >
            <el-image
              v-if="coverUrl"
              :src="coverUrl"
              fit="contain"
              :preview-src-list="[coverUrl]"
              class="cover"
            />
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频上传" prop="name" class="form-item">
          <el-upload
            class="video"
            drag
            action="/"
            :multiple = "false"
            :limit="1"
            :http-request="uploadFile"
            :before-upload="beforeUploadVideo"
            :on-success="handleVideoSuccess"
          >
            <el-icon class="el-icon--upload"></el-icon>
            <div class="el-upload__text">
              请拖拽文件到此处或 <em>点击此处上传视频</em>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listVideo, getVideo, delVideo, addVideo, updateVideo } from "@/api/video/admin";
import {getToken} from "@/utils/auth";
import {checkFile, fileLoad, uploadSliceOne} from "@/api/video/upload";

export default {
  name: "Video",
  data() {
    return {
      now:null,
      videoName:'',
      fileMd5:'',
      coverUrl: '',
      videoUrl:'',
      uploadUrl:  process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 遮罩层
      loading: true,
      loader: null,
      loading3: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      videoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        fileUrl: null,
        disasterId: null,
        picture: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  watch: {
    loader () {
      const l = this.loader
      this[l] = !this[l]

      setTimeout(() => (this[l] = false), 3000)

      this.loader = null
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listVideo(this.queryParams).then(response => {
        this.videoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        fileUrl: null,
        disasterId: null,
        picture: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVideo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {

        if(this.videoUrl===""){
          this.$message.error('视频文件不能为空')
          return
        }
        if(this.videoName===""){
          this.$message.error('视频名字不能为空')
          return
        }
        if(this.coverUrl===""){
          this.$message.error('视频封面不能为空')
          return
        }

        this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVideo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVideo(this.coverUrl,this.videoUrl,this.videoName).then(response => {
              this.videoUrl = ''
              this.videoName = ''
              this.coverUrl = ''
              this.$message.success('发布成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function() {
        return delVideo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/video/export', {
        ...this.queryParams
      }, `video_${new Date().getTime()}.xlsx`)
    },
   uploadFile(params) {
    console.log("uploadFile", params);
    const file = params.file;
    console.log(file.type)
    const formData = new FormData();
    formData.append("file", params.file);
    fileLoad(formData).then(
      res=>{
        this.videoUrl = res.data.url
        console.log(res.data)
      }
    )
    //  const md5S = await md5(file)
    //  this.fileMd5 = md5S
    //  console.log(md5S)
    //  //秒传，如果上传的视频已经存在
    //  if(this.check(md5S)!==false){
    //    this.$message.success('上传成功!');
    //    return;
    //  }
    // console.log("test")
    //  //如果不是大文件，直接上传
    //  const NoSliceSize = file.size / 1024 / 1024 < 50;
    //  if (NoSliceSize) {
    //    const formData = new FormData();
    //    formData.append("file", params.file);
    //    testImg(formData).then(
    //      res=>{
    //        this.videoUrl = res.data.url
    //        this.$message.success('上传成功!');
    //      }
    //    )
    //    return;
    //  }
    //  ////======
    //    const chunkSize = 50*1024*1024;
    //    const totalSize = file.size;
    //    const chunkNum = Math.ceil(totalSize / chunkSize);
    //    console.log(chunkNum+"sadasdad")
    //    //查看该文件是否在上传了一部分(续传)
    //     getSlice(md5S).then(
    //      res=>{
    //        console.log(res.data)
    //        this.now = res.data
    //      }
    //    )
    //    if(this.now==null){
    //      console.log(totalSize)
    //      initTask(md5S,chunkSize,chunkNum,file.size);
    //    }
    //    this.uploadSlice(file)
  },

  check(md5S){
    checkFile(md5S).then(
      res =>{
        this.videoUrl = res.data
        console.log(res.data)
      }
    )
    return this.videoUrl !== "";
  },
  uploadSlice(file){
    const sliceSize = 200;
    const fileSize = file.size / 1024 / 1024; // 获取文件的总大小
    console.log(fileSize)
    const sliceNum = Math.ceil(fileSize / sliceSize); // 计算分片数量
    const fileSlices = new Map(); // 创建一个 Map 对象来存储分片
    for (let i = 0; i < sliceNum; i++) {
      console.log("slice"+i)
      const start = i * sliceSize;
      const end = Math.min(start + sliceSize, fileSize); // 避免超出文件大小
      const slice = file.slice(start, end); // 使用 File API 的 slice 方法获取分片
      fileSlices.set(i, slice); // 将分片存入 Map 对象，key 为分片编号，value 为分片内容
      if(i>=this.now){
        uploadSliceOne(i,slice)
      }
    }
    return fileSlices
  },
  handleCoverSuccess(response) {
    this.coverUrl = response.data.url
    console.log(this.coverUrl)
  },
  handleVideoSuccess(){
    this.$message.success("上传成功")
  },
  beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 5;
    console.log(this.uploadUrl)
    if (!(isJPG || isPNG)) {
      this.$message.error('上传封面图片只能是 JPG 或者 PNG 格式!');
      return false; // 阻止文件上传
    }
    if (!isLt2M) {
      this.$message.error('上传封面图片大小不能超过 5MB!');
      return false; // 阻止文件上传
    }
    return true; // 允许文件上传
  },
  beforeUploadVideo(file) {
    const isMp4 = file.type === 'video/mp4';
    const isMvn = file.type === 'video/mvn';
    console.log(this.uploadUrl)
    if (!(isMp4 || isMvn)) {
      this.$message.error('上传文件只能是 mp4 或者 mvn 格式!');
      return false; // 阻止文件上传
    }
    return true; // 允许文件上传
  }
  }
};
</script>
